/**
 * 线程池封装(处理IO)
 * ***/
const mysql2 = require('mysql2/promise');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

// 创建线程池连接
const poolConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'user',
  port: 3306,
  connectionLimit: 20 // 连接池最大连接数
};

// 请求状态判断
const codeNumber = {
  200: '请求成功',
  201: '处理成功,已创建新资源',
  400: '数据库查询错误',
  401: '用户未授权,请登录',
  500: '服务器内部异常'
};

const pool = mysql2.createPool(poolConfig);
const app = express();

app.use(bodyParser.json()); // 用于解析json數組
app.use(bodyParser.urlencoded({ extended: true })); // 解析value类型 是String和Array

app.use((req, res, next) => {
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
  cors();
  express.json();
  next();
});

/**
 * 查询执行函数
 * @param {String} method 请求类型
 * @param {String} url 请求地址
 * @param {int} numCode http状态值
 * **/
function handleQuery(url, numCode, method) {
  return new Promise((resolve, reject) => {
    app[(method || 'post').toLowerCase()](url, async (req, res) => {
      // resolve({
      //   req: req,
      //   cb: poolMysql,
      //   send: function (code, msgDate, ObjValue, msg) {
      //     res.status(code ? code : numCode).send({
      //       code: numCode,
      //       msg: codeNumber[numCode] || msg || '',
      //       data: {
      //         ...ObjValue,
      //         data: msgDate
      //       }
      //     });
      //   }
      // });
    });
  });
}

// 线程池sql查询
async function poolMysql(sql, values) {
  try {
    const connection = await pool.getConnection();
    const [results] = await connection.execute(sql, values);
    connection.release();
    return results;
  } catch (error) {
    console.log(error);
    return false;
  }
}

// 端口监听
const port = 3000;
app.listen(port, () => {
  console.log('端口开启');
});

module.exports = {
  query: handleQuery,
  poolMysql
};
